<?php

namespace Frieza\Modules\AdServing\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdServing\Channel;
use Doraemon\service\AdServing\ChannelService;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class AdChannelController extends Controller
{
    const PAGE_SIZE = 50;

    const ALABEL = [
        1 => '投放大类',
        2 => '投放渠道',
        3 => '投放位置',
    ];

    /**
     * @param Request $request
     * @param Content $content
     * @param $level
     * @return Content
     */
    public function getList(Request $request, Content $content, $level = 1): Content
    {
        $params = $request->all();
        $params['page'] = $request->input('page', 1);
        $params['per_page'] = $request->input('per_page', self::PAGE_SIZE);
        $params['level'] = $level;

        $data = ChannelService::getFilterData($params);

        $gridModel = new pGridDataModel($data['list'], $data['total'], [
            'perPage' => $params['per_page'],
        ]);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $level) {
            $grid->paginate($gridModel->getPerPage());

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) {
                    $filter->equal('name', '渠道分类名称')->placeholder('请输入中文或英文名称');
                });
                $filter->expand();
            });

            $grid->disableExport();
            $grid->disableRowSelector();

            for ($i = 1; $i < $level; $i++) {
                $grid->column("col_{$i}", self::ALABEL[$i]);
            }

            $grid->column('name', self::ALABEL[$i])->display(function () {
                return $this->name . '(' . $this->code . ')';
            });

            $grid->column('addtime', '创建时间')->display(function () {
                return $this->addtime ? date('Y-m-d H:i:s', $this->addtime) : 0;
            });
            $grid->column('edittime', '更新时间')->display(function () {
                return $this->edittime ? date('Y-m-d H:i:s', $this->edittime) : 0;
            });
        });


        $tab = new Tab();
        for ($i = 1; $i <= 3; $i++) {
            if ($level == $i) {
                $tab->add(self::ALABEL[$i], $listGrid->render(), true);
            } else {
                $tab->addLink(self::ALABEL[$i], "/admin/adServing/channel/tab/{$i}");
            }
        }
        $content->row($tab);

        return $content
            ->header('渠道分类管理')
            ->breadcrumb(['text' => 'APP投放管理']);
    }


    public function editWithLvl(Content $content, int $level = 1, int $id = 0): Content
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑渠道分类';
        } else {
            $title = '创建渠道分类';
        }

        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('渠道分类管理')
            ->breadcrumb(
                [
                    'text' => '渠道分类列表',
                    'url' => "/adServing/channel/tab/{$level}",
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    public function delWithLvl($level, $id): JsonResponse
    {
        $rs = ChannelService::delChannel($id);
        if ($rs === true) {
            return response()->json([
                'status' => true,
                'message' => "删除成功",
            ]);
        } else {
            return response()->json([
                'status' => false,
                'message' => "删除失败," . $rs,
            ]);
        }
    }

    /**
     * @param int $id
     * @return Form
     */
    private function editAction(int $id = 0): Form
    {
        $lvlOptions = [];
        if ($id > 0) {
            $data = Channel::get('*', ['id' => $id]);
            $lvl = $data['level'];
            $lvlOptions = ChannelService::getChannelSelectOptionsByLevel($lvl - 1);

            $form = new Form($data);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->select('level', '渠道分类层级')
            ->required()
            ->options([1 => '一级', 2 => '二级', 3 => '三级'])
            ->load('parent_id', '/admin/adServing/channel/options/');

        $form->select('parent_id', '上级渠道')->options($lvlOptions);

        $form->text('name', '渠道分类中文名')->required('中文名必填')->help('64个字符以下');
        $form->text('code', '渠道分类英文名')->required('英文名必填')->help('64个字符以下');
        $form->text('info', '描述')->placeholder('请输入该数据域的详细信息');

        $form->action('/admin/adServing/channel/save');

        return $form;
    }


    public function save(Request $request)
    {
        $params = $request->all();
        $rs = ChannelService::addChannel($params);
        if ($rs === true) {
            $success = new MessageBag([
                'title' => '保存成功',
            ]);
            $level = $request->input('level', 1);
            return redirect("/admin/adServing/channel/tab/{$level}")->with(compact('success'));
        } else {
            $error = new MessageBag([
                'title' => '保存失败,' . $rs,
            ]);
            return back()->with(compact('error'));
        }
    }

    public function getChannelSelectData(Request $request)
    {
        $level = $request->get('q', 0);
        $aOptions = [];
        if (in_array($level, [1, 2, 3])) {
            $aOptions = ChannelService::getChannelParentSelectOptions($level);
        }
        return $aOptions;
    }
}
